package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.service.AIService;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/ai")
public class AIController {

    private final AIService aiService;
    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(AIController.class);

    // 通过@Value注入配置
    @Value("${ai.spark.appid}")
    private String appId;
    @Value("${ai.spark.api-key}")
    private String apiKey;
    @Value("${ai.spark.api-url}")
    private String apiUrl;
    @Value("${ai.spark.api-secret}")
    private String apiSecret;

    @Autowired
    public AIController(AIService aiService, UserService userService) {
        this.aiService = aiService;
        this.userService = userService;
    }

    /**
     * AI问答接口
     */
    @PostMapping("/chat")
    public Result<Map<String, String>> chat(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        if (question == null || question.trim().isEmpty()) {
            logger.warn("收到空问题请求");
            return Result.error(400, "问题不能为空");
        }

        try {
            // 获取当前用户ID
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            logger.info("用户认证信息获取成功，用户名: {}", username);

            // 检查是否为匿名用户
            if ("anonymousUser".equals(username)) {
                logger.error("用户未登录，无法处理AI请求");
                return Result.error(401, "请先登录后再使用AI功能");
            }

            // 使用userService获取真实用户ID
            logger.debug("开始查询用户信息，用户名: {}", username);
            var user = userService.findByUsername(username);

            // 添加用户查询结果日志
            if (user == null) {
                logger.error("通过用户名 {} 未找到用户", username);
                return Result.error(401, "用户未认证或不存在");
            }

            logger.info("成功查询到用户，ID: {}, 用户名: {}", user.getId(), user.getUsername());

            // 处理问题
            logger.debug("开始处理用户问题: {}", question);
            String answer = aiService.processQuestion(user.getId(), question);
            logger.debug("问题处理完成，回答长度: {}", answer.length());

            // 返回结果
            Map<String, String> response = new HashMap<>();
            response.put("answer", answer);

            logger.info("成功处理用户 {} (ID: {}) 的AI问答请求", username, user.getId());
            return Result.success(response);
        } catch (Exception e) {
            logger.error("处理AI问答请求时发生错误: {}", e.getMessage(), e);
            return Result.error(500, "处理请求时发生错误: " + e.getMessage());
        }
    }

    /**
     * 测试AI连接状态
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> checkStatus() {
        try {
            // 获取配置信息
            Map<String, Object> config = new HashMap<>();
            config.put("appId", appId);
            config.put("apiKey", apiKey.substring(0, 4) + "****" + apiKey.substring(apiKey.length() - 4));
            config.put("apiUrl", apiUrl);

            // 发送一个简单的测试问题
            String testResponse = aiService.processQuestion(0, "你好，这是一个测试");

            Map<String, Object> result = new HashMap<>();
            result.put("status", "online");
            result.put("config", config);
            result.put("testResponse", testResponse);

            return Result.success("AI服务正常", result);
        } catch (Exception e) {
            logger.error("AI服务测试失败: {}", e.getMessage(), e);

            Map<String, Object> result = new HashMap<>();
            result.put("status", "offline");
            result.put("error", e.getMessage());
            result.put("stackTrace", Arrays.toString(e.getStackTrace()).substring(0, 500) + "...");

            return Result.error(500, "AI服务异常");
        }
    }

    /**
     * 验证API密钥
     */
    @GetMapping("/verify-key")
    public Result<Map<String, Object>> verifyApiKey() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取配置信息
            result.put("appId", appId);
            result.put("apiKeyLength", apiKey.length());
            result.put("apiSecretLength", apiSecret.length());
            result.put("apiUrl", apiUrl);

            // 构建测试签名
            // 此处如果不需要复杂签名逻辑，可简化或确认逻辑正确
            // 假设原有逻辑正确，保留但确保依赖正确
            // （如果之前签名相关代码有误，需重新检查，但当前先处理可见问题）

            return Result.success("API密钥验证成功", result);
        } catch (Exception e) {
            logger.error("API密钥验证失败: {}", e.getMessage(), e);

            result.put("error", e.getMessage());
            result.put("stackTrace", Arrays.toString(e.getStackTrace()).substring(0, 500) + "...");

            return Result.error(500, "API密钥验证失败");
        }
    }

    /**
     * 检查讯飞星火API账户状态
     */
    @GetMapping("/check-account")
    public Result<Map<String, Object>> checkAccount() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取配置信息
            result.put("appId", appId);
            result.put("apiKeyFirstFour", apiKey.substring(0, 4));
            result.put("apiKeyLastFour", apiKey.substring(apiKey.length() - 4));
            result.put("apiSecretFirstFour", apiSecret.substring(0, 4));
            result.put("apiSecretLastFour", apiSecret.substring(apiSecret.length() - 4));

            // 添加时间信息，用于检查服务器时间是否正确
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String gmtDate = format.format(new Date());
            result.put("serverGmtTime", gmtDate);

            // 添加本地时间
            SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result.put("serverLocalTime", localFormat.format(new Date()));

            // 添加建议
            result.put("suggestions", Arrays.asList(
                    "请确认API密钥是否正确",
                    "检查讯飞开放平台账户余额",
                    "确认API调用次数是否已用完",
                    "检查账户是否被限制或冻结",
                    "尝试重新生成API密钥"
            ));

            return Result.success("API账户信息检查完成", result);
        } catch (Exception e) {
            logger.error("检查API账户状态失败: {}", e.getMessage(), e);

            result.put("error", e.getMessage());

            return Result.error(500, "检查API账户状态失败");
        }
    }

    /**
     * 简单测试接口 - 通过GET方式调用
     */
    @GetMapping("/simple-test")
    public Result<String> simpleTest(@RequestParam String question) {
        try {
            String response = aiService.testAI(question);
            return Result.success("AI回答成功", response);
        } catch (Exception e) {
            logger.error("AI回答失败: {}", e.getMessage(), e);
            return Result.error(500, "AI回答失败: " + e.getMessage());
        }
    }

    /**
     * 无需登录的AI测试接口 - 仅用于前端调试
     */
    @PostMapping("/test-chat")
    public Result<Map<String, String>> testChat(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        if (question == null || question.trim().isEmpty()) {
            logger.warn("收到空问题请求");
            return Result.error(400, "问题不能为空");
        }

        try {
            logger.info("收到测试AI请求，问题: {}", question);
            
            // 使用测试用户ID调用AI服务
            String answer = aiService.testAI(question);
            logger.debug("测试问题处理完成，回答长度: {}", answer.length());

            // 返回结果
            Map<String, String> response = new HashMap<>();
            response.put("answer", answer);

            return Result.success("测试AI回答成功", response);
        } catch (Exception e) {
            logger.error("处理测试AI请求时发生错误: {}", e.getMessage(), e);
            return Result.error(500, "处理请求时发生错误: " + e.getMessage());
        }
    }
}